package com.alingrad.android.froyoengine.tree;

import javax.microedition.khronos.opengles.GL10;

import com.alingrad.android.froyoengine.collisions.Collidable;
import com.alingrad.android.froyoengine.collisions.Collisions;
import com.alingrad.android.froyoengine.util.FixedSizeArray;

public class FixedSizeObjectManager extends TreeStem {
	protected FixedSizeArray<TreeNode> mObjects;
	private boolean mAlive;
	
	@Override
	public void load(GL10 gl) {
		for (int i = 0; i < mObjects.size(); i++)
			mObjects.get(i).load(gl);
	}

	public FixedSizeObjectManager() {
		super();
		mAlive = true;
		mObjects = new FixedSizeArray<TreeNode>();
	}
	
	public FixedSizeObjectManager(int capacity) {
		super();
		mAlive = true;
		mObjects = new FixedSizeArray<TreeNode>(capacity);
	}
	
	@Override
	public void update(long delta) {
		for (int i = 0; i < mObjects.size(); i++)
			mObjects.get(i).update(delta);
	}

	@Override
	public void addNode(TreeNode node) {
		mObjects.add(node);
	}

	@Override
	public boolean removeNode(TreeNode node) {
		return mObjects.remove(node);
	}

	@Override
	public void cleanNodes() {
		for (int i = 0; i < mObjects.size();) {
			if (!mObjects.get(i).isAlive())
				mObjects.remove(i);
			else
				i++;
		}
	}

	public Collidable checkCollisionsWith(Collidable object1) {
		for (int i = 0; i < mObjects.size(); i++) {
			Collidable object2 = (Collidable)mObjects.get(i);
			if (Collisions.checkCollision(object1, object2))
				return object2;
		}
		return null;
	}
	
	public Collidable checkBoundingBoxCollisionsWith(Collidable object1) {
		for (int i = 0; i < mObjects.size(); i++) {
			Collidable object2 = (Collidable)mObjects.get(i);
			if (Collisions.checkBoundingBoxCollision(object1, object2))
				return object2;
		}
		return null;
	}
	
	@Override
	public void clear() {
		mObjects.clear();
	}

	public int capacity() {
		return mObjects.capacity();
	}

	@Override
	public boolean isAlive() {
		return mAlive;
	}

}
